import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:common/image/image_tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../login/widget/content_text_widget.dart';
import 'user_config.dart';
import 'user_info_edit_info_nick_page.dart';

class UserInfoEditInfoAllPage extends StatefulWidget {
  const UserInfoEditInfoAllPage({super.key});

  @override
  State<UserInfoEditInfoAllPage> createState() => _UserInfoEditInfoAllPageState();
}

class _UserInfoEditInfoAllPageState extends State<UserInfoEditInfoAllPage> {
  String nickname = ''; //昵称
  String sex = ''; //昵称
  String birthday = ''; // 生日
  String constellation = ''; // 星座
  String occupation = ''; // 出生地址
  String occupationCode = '';
  UserConfigData? userConfig;
  String avatarFilePath = '';
  @override
  void initState() {
    fetchEditInfoConfig();
    super.initState();
  }

  /// 计算年龄和星座
  void onConstellation() {
    final date = DateTimeUtils.formatDateStr(birthday, format: 'yyyy-MM-dd');
    int age = getAgeFromBirthdayWithSep(date);
    String constellationStr = getConstellation(DateTimeUtils.getDateTime(birthday.toString())!);
    constellation = '$age | $constellationStr';
  }

  void fetchEditInfoConfig() {
    HttpProvider.get(
      '/user/getEditInfoInit',
      explain: '获取编辑信息初始化数据',
      success: (result) {
        UserConfigData config = UserConfigData.fromJson(result.data);
        userConfig = config;
        nickname = config.nickname?.value ?? '';
        birthday = config.birthday?.value ?? '';
        constellation = '${config.birthday?.subinfo?.age} | ${config.birthday?.subinfo?.ctl}';
        occupation = config.occupation?.value ?? '';
        occupationCode = config.occupation?.subinfo?.cityId ?? '';
        setState(() {});
      },
    );
  }

  void fetchSubmitEditInfo({required String key, required String value}) {
    if (key == 'avatar') {
      HttpProvider.upload(
        '/user/subEditInfo',
        paths: {'avatar': value},
        // params: {'colname': key, 'colvalue': value},
        explain: '用户提交编辑信息',
        send: (count, total) {
          logs('------------上传进度: $count/$total    -----   ${count / total * 100}%');
        },
        success: (result) {},
        failure: (result) {
          Toast.showText(result.message);
        },
      );
    } else {
      HttpProvider.post(
        '/user/subEditInfo',
        params: {'colname': key, 'colvalue': value},
        explain: '用户提交编辑信息',
        success: (result) {},
        failure: (result) {
          Toast.showText(result.message);
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: SafeArea(
        top: false,
        child: Stack(
          children: [
            Image.asset('assets/app/images/auth/background_top_image.png'),
            Scaffold(
              appBar: BrnAppBar(
                title: '个人资料',
                backgroundColor: Colors.transparent,
                // actions: [
                //   Container(
                //     padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 8),
                //     child: BrnSmallMainButton(
                //       width: 50,
                //       title: "保存",
                //       bgColor: const Color(0xFF25D4D0),
                //       themeData:
                //           BrnButtonConfig(smallButtonHeight: 15.h, smallButtonFontSize: 12, smallButtonRadius: 13.r),
                //       insertPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 1),
                //       onTap: () {},
                //     ),
                //   )
                // ],
              ),
              backgroundColor: Colors.transparent,
              body: userConfig == null
                  ? const Center(child: CupertinoActivityIndicator())
                  : Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 32.h),
                          if (userConfig!.avatar!.view == 1)
                            GestureDetector(
                              onTap: () {
                                if (userConfig!.avatar!.edit == 1) {
                                  AssetPickerSheet.showBottomSheet(singleCallback: (String filePath) {
                                    avatarFilePath = filePath;
                                    fetchSubmitEditInfo(key: 'avatar', value: avatarFilePath);
                                  });
                                }
                              },
                              child: Center(
                                  child: userConfig!.avatar!.value!.isEmpty
                                      ? Image.asset('assets/app/images/user_edit/user_edit_camera.png', width: 95.w)
                                      : ImageView(
                                          url: userConfig!.avatar!.value!,
                                          width: 95.w,
                                          shape: BoxShape.circle,
                                          type: ImageViewType.avater,
                                        )),
                            ),
                          SizedBox(height: 32.h),
                          if (userConfig!.nickname!.view == 1)
                            Text(userConfig!.nickname!.title ?? '昵称',
                                style: TextStyle(color: const Color(0xFF000000), fontSize: 13.sp)),
                          if (userConfig!.nickname!.view == 1)
                            ContentTextWidget(
                              top: 5,
                              hintText: '选择设置你的昵称',
                              text: nickname,
                              icon: true,
                              arrow: userConfig!.nickname!.edit == 1,
                              onTap: () {
                                if (userConfig!.nickname!.edit == 1) {
                                  Get.to(UserInfoEditInfoNickPage(
                                    nickname: userConfig!.nickname!,
                                  ))?.then((value) {
                                    if (value != null) {
                                      nickname = value;
                                      setState(() {});
                                    }
                                  });
                                }
                              },
                            ),
                          Container(
                              margin: EdgeInsets.only(top: 15.h),
                              child: Text('性别', style: TextStyle(color: const Color(0xFF000000), fontSize: 13.sp))),
                          ContentTextWidget(
                            top: 5,
                            hintText: '选择您的性别',
                            text: sex,
                            icon: true,
                            arrow: false,
                            onTap: () {
                              SmartDialog.show(
                                usePenetrate: false,
                                clickMaskDismiss: true,
                                backType: SmartBackType.block,
                                keepSingle: true,
                                useAnimation: false,
                                builder: (context) => const Center(
                                  child: CustomAlertWidget(
                                    title: '温馨提示',
                                    content: "不可以更改性别哦~\n",
                                    confirmText: '我知道了',
                                  ),
                                ),
                              );
                            },
                          ),
                          if (userConfig!.birthday!.view == 1)
                            Container(
                                margin: EdgeInsets.only(top: 15.h),
                                child: Text(userConfig!.birthday!.title ?? '年龄',
                                    style: TextStyle(color: const Color(0xFF000000), fontSize: 13.sp))),
                          if (userConfig!.birthday!.view == 1)
                            ContentTextWidget(
                              top: 5,
                              hintText: '选择您的出生日期',
                              text: birthday,
                              content: constellation,
                              icon: true,
                              arrow: userConfig!.birthday!.edit == 1,
                              onTap: () {
                                Birthday birthdayItem = userConfig!.birthday!;
                                if (birthdayItem.edit != 1) {
                                  return;
                                }
                                BottomPickerSheet.showDatePicker(context,
                                    title: '选择生日',
                                    dateType: PickerDateType.YMD,
                                    selectTime: DateTimeUtils.getDateTime(birthdayItem.value.toString()),
                                    maxTime: DateTimeUtils.getDateTime(birthdayItem.dict!.options!.maxyear.toString()),
                                    minTime: DateTimeUtils.getDateTime(birthdayItem.dict!.options!.minyear.toString()),
                                    clickCallBack: (selectValue, selectIndex) {
                                  final date = DateTimeUtils.formatDateStr(selectValue, format: 'yyyy-MM-dd');
                                  int age = getAgeFromBirthdayWithSep(date);
                                  String constellationStr =
                                      getConstellation(DateTimeUtils.getDateTime(selectValue.toString())!);
                                  constellation = '$age | $constellationStr';
                                  setState(() {
                                    birthday = date;
                                  });
                                  fetchSubmitEditInfo(key: 'birthday', value: birthday);
                                });
                              },
                            ),
                          if (userConfig!.occupation!.view == 1)
                            Container(
                                margin: EdgeInsets.only(top: 15.h),
                                child: Text('所在地', style: TextStyle(color: const Color(0xFF000000), fontSize: 13.sp))),
                          if (userConfig!.occupation!.view == 1)
                            ContentTextWidget(
                              top: 5,
                              hintText: '选择您的所在地',
                              text: occupation,
                              icon: true,
                              arrow: userConfig!.occupation!.edit == 1,
                              onTap: () {
                                _invoke();
                              },
                            ),
                        ],
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _invoke() async {
    Toast.showLoading();
    Result result = await HttpProvider.get('/region/getRegList', explain: '获取区域列表');
    Toast.dismiss();
    if (result.code != 0) {
      Toast.showText(result.message);
      return;
    }
    List<dynamic> list = result.data['data'];
    final res = await showModalBottomSheet<CityResult>(
        context: Get.context!,
        builder: (_) {
          return CityPicker(dataList: list);
        });
    logs(res);
    if (res != null) {
      occupation = '${res.province}-${res.city!}';
      occupationCode = res.code.toString();
      setState(() {});
      fetchSubmitEditInfo(key: 'city', value: occupationCode);
    }
  }
}
